package test;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import tool.DBUtil;

public class Logen extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private MannageService manageService;
    private String loggedInUsername; // 新增：用于存储登录成功的用户名
    private Map<String, User> userDataMap; // 新增：用于存储用户数据

    // 新增：单例模式支持
    private static Logen instance;

    // 新增：构造函数改为私有，防止外部直接创建实例
    private Logen() {
        this.setTitle("登录界面");
        this.setSize(300, 200);
        this.setDefaultCloseOperation(3);
        this.setLocationRelativeTo(null);
        JPanel panel = new JPanel();
        panel.setLayout(null);
        JLabel usernameLabel = new JLabel("用户名:");
        this.usernameField = new JTextField(15);
        int labelHeight = (int) ((double) usernameLabel.getPreferredSize().height * 1.4);
        int fieldWidth = (int) ((double) labelHeight * (double) 4.5F);
        this.usernameField.setPreferredSize(new Dimension(fieldWidth, labelHeight));
        this.usernameField.setBounds(100, 25, fieldWidth, labelHeight);
        usernameLabel.setBounds(10, 25, 80, labelHeight);
        JLabel passwordLabel = new JLabel("密码:");
        this.passwordField = new JPasswordField(15);
        this.passwordField.setPreferredSize(new Dimension(fieldWidth, labelHeight));
        this.passwordField.setBounds(100, 50, fieldWidth, labelHeight);
        passwordLabel.setBounds(10, 50, 80, labelHeight);
        JButton loginButton = new JButton("登录");
        loginButton.setBounds(100, 100, fieldWidth, labelHeight);
        panel.add(usernameLabel);
        panel.add(this.usernameField);
        panel.add(passwordLabel);
        panel.add(this.passwordField);
        panel.add(loginButton);
        this.add(panel);
        this.manageService = new MannageService();
        this.userDataMap = new HashMap<>(); // 初始化用户数据映射
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String username = Logen.this.usernameField.getText();
                String password = new String(Logen.this.passwordField.getPassword());
                if ("hjh".equals(username) && "123456".equals(password)) {
                    JOptionPane.showMessageDialog(Logen.this, "管理员登录成功！");
                    Logen.this.setVisible(false);
                    (new admini()).setVisible(true);
                } else if (Logen.this.isValidUser(username, password)) {
                    JOptionPane.showMessageDialog(Logen.this, "用户登录成功！");
                    Logen.this.setVisible(false);
                    loggedInUsername = username; // 存储登录成功的用户名
                    loadUserData(username); // 加载用户数据到内存

                    // 修改: 直接跳转到 Test1 文件展示临时数据
                    new Test1(username).initialize(); // 调用 initialize 方法初始化界面
                } else {
                    JOptionPane.showMessageDialog(Logen.this, "用户名或密码错误！", "错误", 0);
                }
            }
        });
    }

    // 修改方法：加载用户数据到内存，并以数组方式存储
    private void loadUserData(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM 关于用户 WHERE User = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                User user = new User();
                user.setUsername(rs.getString("User"));
                user.setPassword(rs.getString("pword"));
                user.setWaterUsage(rs.getDouble("water"));
                user.setElectricityUsage(rs.getDouble("elec"));

                // 新增：读取缴费状态字段
                user.setWaterPayState(rs.getString("WaterPayState"));
                user.setElecPayState(rs.getString("ElecPayState"));
                user.setWuPayState(rs.getString("WuPayState"));

                // 将用户数据存储为数组
                String[] userDataArray = new String[7]; // 扩展数组大小以容纳新字段
                userDataArray[0] = user.getUsername();
                userDataArray[1] = user.getPassword();
                userDataArray[2] = String.valueOf(user.getWaterUsage());
                userDataArray[3] = String.valueOf(user.getElectricityUsage());
                userDataArray[4] = user.getWaterPayState();
                userDataArray[5] = user.getElecPayState();
                userDataArray[6] = user.getWuPayState();

                // 存储到 userDataMap 中
                userDataMap.put(username, user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载用户数据失败: " + e.getMessage(), "错误", 0);
        } finally {
            DBUtil.closeConnection(conn);
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 修改方法：获取用户数据
    public static User getUserData(String username) {
        // 使用静态变量存储 Logen 实例，确保 userDataMap 被正确初始化
        if (instance == null) {
            instance = new Logen();
        }
        return instance.userDataMap.get(username);
    }

    // 内部类：表示用户数据
    static class User {
        private String username;
        private String password;
        private double waterUsage;
        private double electricityUsage;
        private String waterPayState; // 新增：水费缴费状态
        private String elecPayState;  // 新增：电费缴费状态
        private String wuPayState;    // 新增：物业费缴费状态

        // Getters and Setters
        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public double getWaterUsage() {
            return waterUsage;
        }

        public void setWaterUsage(double waterUsage) {
            this.waterUsage = waterUsage;
        }

        public double getElectricityUsage() {
            return electricityUsage;
        }

        public void setElectricityUsage(double electricityUsage) {
            this.electricityUsage = electricityUsage;
        }

        // 新增：Getters and Setters for new fields
        public String getWaterPayState() {
            return waterPayState;
        }

        public void setWaterPayState(String waterPayState) {
            this.waterPayState = waterPayState;
        }

        public String getElecPayState() {
            return elecPayState;
        }

        public void setElecPayState(String elecPayState) {
            this.elecPayState = elecPayState;
        }

        public String getWuPayState() {
            return wuPayState;
        }

        public void setWuPayState(String wuPayState) {
            this.wuPayState = wuPayState;
        }
    }

    private boolean isValidUser(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        boolean var7;
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM 关于用户 WHERE User = ? AND pword = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            var7 = rs.next();
            return var7;
        } catch (SQLException e) {
            e.printStackTrace();
            var7 = false;
        } finally {
            DBUtil.closeConnection(conn);

            try {
                if (pstmt != null) {
                    pstmt.close();
                }

                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

        return var7;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                (new Logen()).setVisible(true);
            }
        });
    }
}
